#!/usr/bin/env python
# encoding: utf-8
'''
@author: wangjianrong
@software: pycharm
@file: 子进程.py
@time: 2020/9/24 9:12
@desc:
'''

import subprocess


ret = subprocess.call(['ls','-l'],shell=True)
print(ret)

ret = subprocess.check_call(['ls','-l'])
print(ret)

ret = subprocess.check_output(['ls','-l'])
print(ret)

def create_subprocess(times=1,url='baidu.com'):
    child = subprocess.Popen(['ping', '-c', str(4-times), url])
    print('{}'.format(times)*10)
    return child

#check_output、check_call、call都是基于Popen的封装
# child = subprocess.Popen(['ping','-c','4','baidu.com'])
# child.wait()
url='baidu.com'
processes = []
for i in range(3):
    times = i + 1
    processes.append(create_subprocess(times,url))

for i,process in enumerate(processes):
    times = i + 1
    cmd = ['ping', '-c', str(4 - times), url]
    process.wait()
    if process.returncode != 0:
        raise subprocess.CalledProcessError(returncode=process.returncode,cmd=cmd)
print('finish')


# child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
# print(child1.stdout.read())

# subprocess.PIPE实际上为文本流提供一个缓存区。child1的stdout将文本输出到缓存区，随后child2的stdin从该PIPE中将文本读取走。child2的输出文本也被存放在PIPE中，直到communicate()方法从PIPE中读取出PIPE中的文本。
# 注意：communicate()是Popen对象的一个方法，该方法会阻塞父进程，直到子进程完成
child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE,encoding="utf-8")
child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE,encoding="utf-8")
out = child2.communicate()
print(out)
# print(str(out[0],encoding='utf-8'))
# print(child2.stdout.read())

def runcmd(command):
    ret = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1)
    if ret.returncode == 0:
        print("success:",ret)
    else:
        print("error:",ret)


runcmd(["dir","/b"])#序列参数
runcmd("exit 1")#字符串参数

